<template>
    <div class="out-card">
      <div class="card-content">
        <div class="table-common">
          <el-tabs class="demo-tabs" v-model="activeTab"  @tab-click="checkTab">
            <el-tab-pane label="受理列表" name="accept" >
            </el-tab-pane>
            <el-tab-pane label="挂起列表" name="hangUp"></el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
  <layout-card :filters="repairManagementQuery" headline="信息列表" @update:modelValue="handlerUpdateModelValue"
    @search-reset="searchReset" @change="change">

    <template #action>
      <el-button type="primary" @click="Export()">导出</el-button>
      <el-button type="primary" @click="() => openAddDialog()">新增</el-button>
    </template>
    <table-common :columns="examplemanagement" :loading="loading" :pagination="pager" :table-data="tableData" size="large"
      @current-change="currentChange" @size-change="sizeChange">
      <!-- 数据 -->
      <template #urgency="{ row }">
        <span>{{ row.urgency == 1 ? '非常紧急' : row.urgency == 2 ? '一般紧急' : '一般' }}</span>
      </template>
      <!-- 设备类型 -->
      <template #eqptTypeName="{ row }">
        <span v-if="row.eqptTypeId === '0'">{{ row.eqptTypeOtr }}</span>
        <span v-else>{{ row.eqptTypeName }}</span>
      </template>

      <!-- 报修人 -->
      <template #repName="{ row }">
        <span>{{ row.creator.name }}</span>
      </template>
      <template #repNamerowphone="{row}">
        <span>{{ row.creator.phone }} </span>
      </template>
      <!-- 接收单位 -->
      <template #organId="{ row }">
        <span v-if="row.organType === '1'">{{ Treedata(row.organId) }}</span>
        <span v-else>{{ exterior(row.organId) }}</span>
      </template>
      <!-- 报修单位 -->
      <template #createUserOrgId="{ row }">
        <span>{{ row.creator.organName }}</span>
      </template>
      <!-- 状态 -->
      <template #repApplyState="{ row }">
        <span :class="row.repApplyState === '03' ? 'active' : ''">{{ repState(row.repApplyState) }}</span>
      </template>
      <!-- 操作 -->
      <template #action="{ row }">
        <el-button @click="openEditDialog(row)" link type="primary">查看</el-button>
        <el-button @click="edits(row)" link type="primary" v-if="row.repApplyState === '03'">编辑</el-button>
        <el-button @click="Process(row)" v-if="row.repApplyState==='03'" link type="primary" main>流程追踪</el-button>
      </template>
    </table-common>
  </layout-card>
  <!-- 新增弹框 -->
  <Add :visible="centerDialogVisible" @cancel="cancel" @showAdd="handleShowAdd"></Add>
  <!-- 查看,编辑 -->
  <edit :visible="editVisible" :type="type" :data="list" @cancel="cancel" @showAdd="handleShowAdd"></edit>
  <!-- 流程追踪 -->
  <el-dialog
      v-model="modalProcessVisible"
      title="流程追踪"
      width="30%"
      draggable
      :show-close="false"
      class="elDialog"
    >
      <el-timeline>
        <el-timeline-item
          v-for="(activity, index) in modalProcessTracingData"
          :key="index"
          :timestamp="`${activity?.createTime}  ${
            RepAcceptState?.[activity?.nodeState]
          }`"
          hollow
        >
          <div>
            {{ activity?.creator?.name }}
            <span :style="{ paddingLeft: '6px', color: '#919399' }">
              {{ activity?.creator?.organName }}
            </span>
          </div>
          <div
            v-if="
              activity?.nodeContent?.reject || activity?.nodeContent?.suspend
            "
               class="Showhide">
            审批意见：
            {{
              activity?.nodeContent?.reject || activity?.nodeContent?.suspend
            }}
          </div>
        </el-timeline-item>
      </el-timeline>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="modalCancel">关闭</el-button>
        </span>
      </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onBeforeMount, computed, watch} from 'vue'
import LayoutCard from '@/components/LayoutCard/index.vue'
import { useRepairManagementQuery } from './config/filter'
import { examplemanagement } from './config/columns'
import TableCommon from '@/components/TableCommon/index.vue'
import Add from './add.vue'
import edit from './edit.vue'
import { repairList, Exportapi, getcompanys,repairReject } from '@/api/requst/management'
import { useStore } from 'vuex'
import { ElMessage, dayjs } from 'element-plus'
import { repairNodeFind } from '@/api/maintenance/repairacceptancemanagement/services'
// import { RepAcceptState } from '../repairacceptancemanagement/config/utils'

const search = ref({})
let type = ref(0)
const loading = ref(true)
const $store = useStore()
let list = ref()
const modalProcessVisible = ref(false);
const allOrganTree = computed(() => $store.state.user.allOrganTree);
const Users = computed(() => $store.getters["user/getUserInfo"]);
const { repairManagementQuery } = useRepairManagementQuery()
const modalProcessTracingData = ref<any>([]);
// console.log(RepAcceptState?.[activity?.nodeState]);
const activeTab = ref("");




const RepAcceptState: any = {
  "00":"发起维修",
  "01": "待指派",
  "02": "待领取",
  "03": "待维修",
  "04": "待验收",
  "05": "已完结",
  "06": "挂起",
  "07":"退回"
};

const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const info = ref(null)
// 新增弹窗是否打开
const centerDialogVisible = ref(false)
// 编辑
const editVisible = ref(false)
const tableData = ref<any[]>([])
// const list = ref([])
const payload = reactive({
  pageNum: pager.currentPage,
  pageSize: pager.pageSize,
  condition: {
    repCode: null,
    eqptTypeId: null,
    problemId: null,
    order:[{ column: 'rep_apply_state', method:'desc' }],
    createUserOrgId: null,
    createUserName: null,
    createEndTime: null,
    createStartTime: null,
    urgency: null,
    organId: null,
    eqptFloor: null,
    repApplyState: null,
    terminal: null
  }
})
// 信息列表
const getData = async () => {
  if(payload.condition.repApplyState!='02'&&payload.condition.repApplyState!='04'){
    activeTab.value=''
  }
  await repairList(payload).then((res: any) => {
    if (res?.code === '1') {
      tableData.value = res.data.list
      console.log(res.data.list);
      loading.value = false
      pager.total = res.data.total
    }
  })
  
}

const checkTab=(tab:any)=>{
  console.log(tab,'tab');
  
  if(tab.paneName=='hangUp'){
    payload.condition.repApplyState='04'
  }
  if(tab.paneName=='accept'){
    payload.condition.repApplyState='02'
  }
 
  getData()
  
}
// getData()
// 分页
const sizeChange = (size: number) => {
  pager.pageSize = size
  payload.pageSize = pager.pageSize
  console.log(payload.pageSize, 'payload.pageSize');
  getData()
}

const currentChange = (value: number) => {
  pager.currentPage = value
  payload.pageNum = pager.currentPage
  console.log(payload.pageNum, 'payload.pageNum');

  getData()
}
//导出
const Export = async () => {
  //查询无数据时11
  if (tableData.value.length === 0) {
    ElMessage.error('无数据导出')
    return
  }
  const exports =   payload.condition 
  await Exportapi(exports).then((res: any) => {
    console.log(res, 'res');

    const fileName = `报修管理${dayjs(new Date()).format('YYYYMMDD')}.xlsx`// 自定义文件名
    const blob = new Blob([res], {
      type: 'application/vnd.ms-excel;charset=utf-8'// 文件格式
    })
    const link = document.createElement('a')// 创建下载链接
    link.href = URL.createObjectURL(blob)
    link.download = `${fileName}`
    link.click()
    URL.revokeObjectURL(link.href)
    link.remove()

  }).catch(err => {
    ElMessage.error(err.message || '导出失败')
  })
}
//添加
const openAddDialog = (row = null) => {
  console.log(row)
  centerDialogVisible.value = true
  info.value = row
}
//查看
const openEditDialog = (row: any) => {
  list.value = row
  editVisible.value = true
  type.value = 1
}
//编辑
const edits = (row: any) => {
  list.value = row
  editVisible.value = true
  type.value = 2
}

const modalCancel = () => {
  modalProcessVisible.value = false;
};

const lastMender = computed(() => {
  return {
    id: Users.value?.userId,
    name: Users.value?.userName,
    phone: Users.value?.phone,
    organId: Users.value?.organId,
    organName: Users.value?.organName,
  };
});



//流程追踪
const Process= async(row:any)=>{
  modalProcessVisible.value=true
  try {
    const res = await repairNodeFind({
      repId: row?.repId,
      mender: lastMender.value,
    });
    modalProcessTracingData.value = res.data;
    modalProcessVisible.value = true;
  } catch (error: any) {
    ElMessage.error(error?.message);
  }
}


onBeforeMount(() => {
  // 加载列表数据
  Promise.all([$store.dispatch('user/getOrgan'), $store.dispatch('repair/setTerminal'), $store.dispatch('repair/setPrograms'), $store.dispatch('repair/setEqptTypes'), $store.dispatch('repair/setCompanys')]).then(res => {
    getData()
  })
})
//弹框点击消失
const cancel = () => {
  centerDialogVisible.value = false
  editVisible.value = false
  getData()
}
const handleShowAdd = () => {
  centerDialogVisible.value = false
}

// 清空
const searchReset = (data: FilterDataType) => {
  pager.currentPage = 1
  pager.pageSize = 10
  payload.pageSize = pager.pageSize
  payload.pageNum = pager.currentPage
  getData()
}

let OrganTreedata:any[]=[]
// 格式化接收单位(内部单位)
if($store.getters['user/getAllOrganTree'] && $store.getters['user/getAllOrganTree'].length>0 ){
   OrganTreedata = $store.getters['user/getAllOrganTree'][0].children[0].children 
}else{
  OrganTreedata=[]
}

const Treedata = (organId: any) => {
  const organname = OrganTreedata.find((item: any) => item.value === organId)?.label
  return organname
}
//外部单位
const exterior=(organId: any)=>{
  const companyName = $store.getters['repair/getCompanyse']
  const companyNames = companyName.find((item: any) => item.companyId === organId)?.companyName
  return companyNames
}



//查询 
const handlerUpdateModelValue = (data: any) => {
  payload.condition.repCode = data.repCode
  payload.condition.eqptTypeId = data.eqptTypeId
  payload.condition.problemId = data.problemId
  payload.condition.createUserOrgId = data.createUserOrgId
  payload.condition.createUserName = data.createUserName
  payload.condition.urgency = data.urgency
  payload.condition.organId = data.organId
  payload.condition.eqptFloor = data.eqptFloor
  payload.condition.repApplyState = data.repApplyState
  // 航站楼
  if (data.terminal && data.terminal.length >= 0) {
    payload.condition.terminal = data.terminal.join(',')
  }


  // 报修时间
  if (data.repairtime) {

    payload.condition.createStartTime = data.repairtime[0]
    payload.condition.createEndTime = data.repairtime[1]
  } else {
    payload.condition.createStartTime = null
    payload.condition.createEndTime = null
  }

  getData()

}

//监听变化
const change=(data:any)=>{
  $store.commit('repair/SET_ascription', data.srcElement._value)
  
}

const repState = (row: string) => {
  if (row === '01') {
    return '待分析'
  }
  if (row === '02') {
    return '已受理'
  }
  if (row === '03') {
    return '已驳回'
  }
  if (row === '04') {
    return '已挂起'
  }
}

</script>

<style scoped lang="less">
.active {
  color: orange;
}
.Showhide{
  width: 80%;
  white-space: nowrap;
  /*2. 超出的部分隐藏*/
      overflow: hidden;
  /*3. 文字用省略号替代超出的部分*/
      text-overflow: ellipsis;
}
.out-card {
    background: #f5f7f9;
    overflow: hidden;
    @titleFontFamily: 'HarmonyOS_Sans_SC_Medium';

    .card-content {
        padding: 12px;
        margin: 12px 12px 0;
        background: #fff;
        border-radius: 8px;

        &.card-search {
            padding-bottom: 0;
        }

        .content-bar {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 24px;

            .title {
                font-size: 16px;
                font-family: @titleFontFamily;
                color: #353a42;
                line-height: 24px;
                font-weight: bolder;
            }
        }
    }
}
</style>